#pragma once
#include "public.hpp"

using namespace std;

using task_t = function<void()>;

class MessageRoute
{
private:
    vector<Analyze> user;

    bool IsExist(const Analyze& temp)
    {
        for(auto &e : user)
        {
            if(e == temp)
                return true;
        }

        return false;
    }

public:

    void AddUser(const Analyze& temp)
    {
        if(IsExist(temp)) return;
        user.push_back(temp);
    }

    void DelUser(const Analyze& temp)
    {
        for(auto e = user.begin(); e != user.end(); e++)
        {
            if(*e == temp)
            {
                user.erase(e);
                return;
            }
        }
    }

    void Routedo(int sockfd, string message)
    {
        for(auto &e : user)
        {
            struct sockaddr_in addr = e.getsock();
            sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&addr, sizeof(addr));
        }      
    }

    void Route(int sockfd, string message, const Analyze who)
    {
        AddUser(who);

        if(message == "quit")
            DelUser(who);
        
        task_t task = bind(&MessageRoute::Routedo, this, sockfd, message);
        ThreadPool<function<void()>>::GetPool()->Push(task);
    }

};